#!/bin/bash

curdir=$(dirname $0)

ce_project="gitlab-foss"
ee_project="gitlab"
group_name="gitlab-org"

if [ "${ASSET_REGISTRY}" = "dev.gitlab.org:5005" ]
then
  group_name="gitlab"
  ce_project="gitlabhq"
  ee_project="gitlab-ee"
fi

if [[ -n "${TOP_UPSTREAM_SOURCE_PROJECT}" && "${TOP_UPSTREAM_SOURCE_PROJECT}" =~ gitlab-org/(security/)?gitlab ]]
then
  project_path="${TOP_UPSTREAM_SOURCE_PROJECT}"
elif ${curdir}/is_gitlab_ee.sh
then
  project_path="${group_name}/${ee_project}"
else
  project_path="${group_name}/${ce_project}"
fi

if ${curdir}/is_gitlab_ee.sh
then
  assets_image="${project_path}/gitlab-assets-ee"
else
  assets_image="${project_path}/gitlab-assets-ce"
fi

gitlab_version=$(echo "${1}" | awk '
  {
    gsub(/[^a-z0-9]/, "-")
    gsub(/(^-+|-+$)/, "")
    print substr($0, 1, 63);
  }
')

docker login -u gitlab-ci-token -p ${CI_JOB_TOKEN} ${CI_REGISTRY}

assets_image_name="${ASSET_REGISTRY}/${assets_image}:${gitlab_version}"

# In case the image hasn't been created yet. Keep trying until the pipeline times out
interval=30
while ! docker pull "${assets_image_name}"
do
  echo "${assets_image_name} is not available yet. Will retry in ${interval} seconds"
  sleep ${interval}
done

docker create --name asset_cache "${assets_image_name}"
docker cp asset_cache:/assets ${ASSET_PATH}
